package cn.deschen.eshop.auth.filter;

import cn.deschen.eshop.auth.enums.ValidateCodeTypeEnum;
import cn.deschen.eshop.auth.properties.SecurityProperties;
import cn.deschen.eshop.auth.validate.ValidateCodeProcessor;
import cn.deschen.eshop.auth.validate.ValidateCodeProcessorHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.ServletWebRequest;
import org.springframework.web.filter.OncePerRequestFilter;
import org.springframework.stereotype.Component;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author hanbin_chen
 * @Description 验证码权限过滤器
 * @DateTime 2021/1/14 9:18
 * @Version V1.0.0
 */
@Slf4j
@Component
public class ValidateCodeFilter extends OncePerRequestFilter implements InitializingBean {

    @Autowired
    private SecurityProperties securityProperties;

    @Autowired
    private ValidateCodeProcessorHolder validateCodeProcessorHolder;

    private Map<String, ValidateCodeTypeEnum> urlMap = new HashMap<>(16);

    /**
     * 对bean做属性配置然后最终实例化
     *
     * @throws ServletException
     */
    @Override
    public void afterPropertiesSet() throws ServletException {
        super.afterPropertiesSet();

        // 添加自定义拦截请求与类型的映射
        addUrlToMap(
                securityProperties.getBrowser().getUserPwd().getValidateUrl(), ValidateCodeTypeEnum.IMAGE);
        addUrlToMap(
                securityProperties.getBrowser().getMobile().getValidateUrl(), ValidateCodeTypeEnum.SMS);
    }

    private void addUrlToMap(String url, ValidateCodeTypeEnum codeTypeEnum) {
        urlMap.put(url, codeTypeEnum);
    }

    /**
     * 每个请求只拦截一次处理
     *
     * @param request
     * @param response
     * @param filterChain
     * @throws ServletException
     * @throws IOException
     */
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        log.info("【权限模块】请求路径url = {}", request.getRequestURI());
        // 根据请求判断校验类型
        ValidateCodeTypeEnum codeTypeEnum = getValidateCodeTypeEnum(request);

        // 判断验证码类型是不是验证码校验的接口，不是则跳过认证处理
        if (null != codeTypeEnum) {
            // 根据类型做对应的验证码处理器
            ValidateCodeProcessor validateCodeProcessor = validateCodeProcessorHolder.getValidateCodeProcessor(codeTypeEnum);
            // 对验证码进行处理
            validateCodeProcessor.validateCode(new ServletWebRequest(request, response), codeTypeEnum);
        }

        filterChain.doFilter(request, response);
    }

    /**
     * 获取请求的验证类型。如果请求不需要校验，则返回null
     *
     * @param request
     * @return
     */
    private ValidateCodeTypeEnum getValidateCodeTypeEnum(HttpServletRequest request) {
        ValidateCodeTypeEnum validateCodeTypeEnum = null;
        // 判断是否是Post请求
        if ("POST".equalsIgnoreCase(request.getMethod())) {
            // 通过urlMap获取相应的类型
            for (Map.Entry<String, ValidateCodeTypeEnum> entry :
                    urlMap.entrySet()) {
                if (entry.getKey().matches(request.getRequestURI())) {
                    validateCodeTypeEnum = entry.getValue();
                    break;
                }
            }
        }

        log.info("请求路径 = {}，请求方式 = {}， 类型 = {}", request.getRequestURI(), request.getMethod(), validateCodeTypeEnum);
        return validateCodeTypeEnum;
    }
}


